<?php

namespace Admin\Controller;

use Utuo\BackgroundController;
use Utuo\Region;
use Utuo\Phpass;

class CustomerController extends BackgroundController {
	
	private $cid = 0;
	
	private $table = array();
	
	// 技术支持显示类型(0=自动,9=不显示,1=系统,2=合作商,3=客户)
	private $supportTypes = array(
	    0=>'自动',
	    1=>'系统',
	    2=>'合作商',
	    3=>'客户',
	    9=>'不显示'
	);
	
	// 初始化
	public function _initialize() {
		$this->cid = I("id", 0, "intval");
		$this->setControllerTitle('客户管理');
		$this->setActionTitle(array(
				'index' => '客户列表',
				'add' => '添加客户',
				'modify' => '修改客户',
				'customerManagerConfig' => '用户登录后台配置',
				'recycle' => '回收站',
		    'finance'=>'财务管理'
		));
		$this->setActionNav(array(
				'index',
				'add',
				'recycle',
		));
		$this->table = array('role'=>C('RBAC_ROLE_TABLE'),'user'=>C('RBAC_USER_TABLE'),'access'=>C('RBAC_ACCESS_TABLE'),'node'=>C('RBAC_NODE_TABLE'));
	}
	
	// 财务
	public function financeAction(){
	    $this->cid = I('cid',0,'intval');
	    $customer = M('Customer')->find($this->cid);
	    $config = M('Config')->find();
	    
	    $totalMoney = M('CustomerFinance')->where('cid=%d',$this->cid)->sum('money');
	    $customer['totalMoney'] = $totalMoney ? $totalMoney : 0;
	    
	    $pvDays = M('CustomerReport')->where("cid=%d",$this->cid)->count();
	    $customer['pv_avg'] = ceil($customer['pv']/$pvDays);
	    
	    // 最近7天流量记录
	    $reports = M('CustomerReport')->where(array('cid'=>$this->cid))->limit(7)->order("id DESC")->select();
	    
	    if ($pvDays<=7){
	        $customer['pv_week_avg'] = $customer['pv_avg'];
	    } else {
	        // 最近7天的总流量
	        $pvWeekCount = 0;
	        foreach ($reports as $v){
	            $pvWeekCount+= $v['pv'];
	        }
	        $customer['pv_week_avg'] = ceil($pvWeekCount/7);
	    }
	    $customer['pv_rest'] = $customer['pv_count'] + $customer['pv_default'] - $customer['pv'];
	    $customer['day_rest'] = $customer['pv_week_avg'] ? number_format($customer['pv_rest'] / $customer['pv_week_avg'],1) : '>9999';
	    
	    $this->assign('customer',$customer);
	    $this->assign('config',$config);
	    $this->assign('reports',$reports);
	    $this->assign('sid',$this->cid);
	    $this->display();
	}
	
	// 提交充值
	public function saveFinanceAction(){
	    $m = M('CustomerFinance');
	    if ($m->create()){
	        $m->create_time = time();
	        $m->admin_id = $this->aid;
	        $m->admin_ip = get_client_ip();
	        $cid = $m->cid;
	        $pv = $m->pv;
	        if ($m->add()){
	            M('Customer')->where("id=%d",$cid)->setInc("pv_count",$pv);
	            $this->ajaxSuccess('充值成功');
	        } else {
	            $this->ajaxError('充值失败');
	        }
	    } else {
	        $this->ajaxError('提交数据错误');
	    }
	}
	
	// 超级登录
	public function loginAction() {
		$id = I("id", 0, "intval");
		$cid = I("cid", 0, "intval");
		$cid and $id = M("CustomerAdmin")->where('cid=%d and is_super=1', $cid)->getField('id');
		$customer = M("CustomerAdmin a")->join("__CUSTOMER__ b on a.cid=b.id", "LEFT")->where("a.id={$id}")->field('a.*,b.partner')->find();
		$cid = $cid ? $cid : $customer['cid'];
		$_SESSION["_my_"] = array(
			"userid" => $customer['id'],
			"id" => $cid,
		    "pid" => $customer['partner'],
			"name" => $customer['name']."(".session("name").")",
			"customerManagerConfig" => null,
			self::LOGIN_TIME => time(),
			self::LAST_ACTIVE => time(),
			self::IS_LOGINED => true,
		);
		$_SESSION["_my_"]["sessionKeys"] = serialize( array_keys($_SESSION["_my_"] ) );
		redirect(U("My/Index/index"), 0);
	}
	
	// 客户列表
	public function indexAction() {
		$this->getList(0);
	}
	
	// recycle of customer to display
	public function recycleAction() {
		$this->getList(1);
	}
	
	/**
	 * display the customer list
	 * @param unknown $is_deleted 是否已删除
	 */
	private function getList($is_deleted) {
		/*查询条件*/
		$name = I('name', "");
		/*有条件查询*/
		$condition = array(
			"this0.is_deleted" => $is_deleted
		);
		$param = array();
		$name and $condition['this0.name'] = array('like', "%$name%") and $param['name'] = $name;
		/*搜索*/
		$p = $this->getPage();
		$pageSize = $this->getPageSize();
		$customerListSql = M()->table("__CUSTOMER__ this0")->join('LEFT JOIN __CN_PROVINCE__ this1 on this0.province=this1.code')
							->join('LEFT JOIN __CN_CITY__ this2 on this0.city=this2.code')
							->join('LEFT JOIN __CN_AREA__ this3 on this0.area=this3.code')
							->join('LEFT JOIN __PARTNER__ this4 on this0.partner = this4.id')
							->field("this0.*,this1.name as provinceName,this2.name as cityName,this3.name as areaName,this4.name as partnerName")
							->select(false);
		$customerLists = M()->table($customerListSql." this0")->where($condition)->limit($pageSize)->page($p)->order('id DESC')->select();
		$count = M()->table($customerListSql." this0")->where($condition)->count();
		$this->assign("customerLists", $customerLists);
		$this->assign("param", $param);
		$this->showPage($count, $pageSize, $param);
		$this->display();
	}
	
	// to custormer's add page
	public function addAction() {
		$partnerLists = M("Partner")->where('is_deleted=0')->getField('id,name');
		$this->partnerOptions = $this->getOption($partnerLists,null,'==请选择合作商==');
		$this->provinceOptions = $this->getOption(Region::getProvinceList(), null, '==请选择省份==');
		$this->cityOptions = $this->getOption(array(), null, '==请选择城市==');
		$this->areaOptions = $this->getOption(array(), null, '==请选择地区==');
		$this->display();
	}
	
	// add post
	public function addPostAction() {
		$d = D("customer");
		if ($d->create()) {
			if (!empty($d->password)) {
				$d->password = Phpass::hash($d->password);
			} else{
				$this->ajaxError("密码不能为空!");
			}
			$d->pv_count = M('Config')->getField("free_pv");
			$dd = clone $d;
			if ($cid = $d->add()) {
				false !== M("CustomerAdmin")->add( array(
					'cid' => $cid,
					'name' => $dd->name,
					'email' => $dd->email,
					'password' => $dd->password,
					'last_login_time' => 0,
					'last_login_ip' => '',
					'login_count' => 0,
					'is_role' => 0,
					'is_super' => 1,
				)) and $this->ajaxSuccess();
			}
			$this->ajaxError();
		} else {
			$this->ajaxError($d->getError());
		}
	}
	
	// redirect to modify page
	public function modifyAction() {
		$customer = $this->getOneById("customer");
		$partnerLists = M("Partner")->where('is_deleted=0')->getField('id,name');
		$customer['partnerOptions'] = $this->getOption($partnerLists, $customer['partner'], '==请选择合作商==');
		$customer['provinceOptions'] = $this->getOption(Region::getProvinceList(), $customer['province'], '==请选择省份==');
		$customer['cityOptions'] = $this->getOption(Region::getCityListByProvince($customer['province']), $customer['city'], '==请选择城市==');
		$customer['areaOptions'] = $this->getOption(Region::getAreaListByCity($customer['city']), $customer['area'], '==请选择地区==');
		$customer['supportTypeOptions'] = $this->getOption($this->supportTypes,$customer['support_type']);
		$this->assign("customer", $customer);
		$this->display();
	}
	
	// modify customer and execute
	public function modifyPostAction() {
		$d = D("Customer");
		if ($d->create()) {
			if (empty($d->password)) {
				unset($d->password);
			} else{
				$d->password = Phpass::hash($d->password);
			}
			if (false!==$d->save()) {
				$this->ajaxSuccess();
			} else {
				$this->ajaxError();
			}
		} else {
			$this->ajaxError($d->getError());
		}
	}
	
	// remove customer
	public function removePostAction() {
		$this->ajaxRemove();
	}
	
	// restore customer
	public function restorePostAction() {
		$this->ajaxRestore();
	}
	
	// delete customer;
	public function deletePostAction() {
		$this->ajaxDelete();
	}
	
	// status update
	public function setStatusPostAction() {
		$id = I("id", 0, "intval");
		$status = I("status", 0, "intval");
		$customer = M("customer");
		if ($customer->where("id={$id}")->setField("status", 1 - $status)) {
			$this->ajaxSuccess();
		} else {
			$this->ajaxError($customer->getError());
		}
	}
	
	// 获取城市
	public function getCityPostAction() {
		echo $this->getOption(Region::getCityListByProvince(I('code')), '', '==请选择城市==');
	}
	
	// 获取地区
	public function getAreaPostAction() {
		echo $this->getOption(Region::getAreaListByCity(I('code')), '', '==请选择地区==');
	}
	
	/*public function setRoleAction($cid){
		$partner=M('customer')->where('id=%d',$cid)->getField('partner');
		$role=M('Role')->where('is_deleted=%d and partner_id=%d',0,$partner)->getField('id,name');
		$roleCus=M('RoleCustomer')->where('customer_id=%d',$cid)->getField("role_id",true);
		$fid=M('customer')->where('id='.$cid)->getField("fid");
		if($fid && !$roleCus)
		{
			$roleArray=M('RoleCustomer')->where('customer_id=%d',$fid)->getField("role_id",true);
			$array=array();
			foreach ($roleArray as $v)
			{
				$array[]=array('role_id'=>$v,'customer_id'=>$cid);
			}
			M('RoleCustomer')->addAll($array);
			$cid=$fid;
		}
		$roleids=D('RoleCustomer')->where('customer_id=%d',$cid)->getField("role_id",true);
	
		$data['roleCheckbox']=\Utuo\Form::makeCheckbox($role,$roleids,'role_id[]');
		$data['cid']=$cid;
		$this->assign("data",$data);
		$this->display();
	}
	
	public function saveRoleAction(){
		$cid=I('cid');
		$role_ids=I('role_id');
		D('RoleCustomer')->where('customer_id=%d',$cid)->delete();
		if(is_array($role_ids))
		{
			foreach ($role_ids as $v)
			{
				D('RoleCustomer')->add(array(
				'customer_id'=>$cid,
				'role_id'=>$v
				));
	
			}
			$this->ajaxSuccess();
		}
		$this->ajaxError();
	
	}*/
	
	//是否开启角色分配
	public function isRoleAction($adminCid, $isrole) {
		M('CustomerAdmin')->where('id=%d', $adminCid)->setField("is_role",$isrole)?$this->ajaxSuccess():$this->ajaxError();
	}
}